#include <iostream>
#include <queue>
using namespace std;
int DIS(int a, int b, int c, int d) {
    return abs(a - c) + abs(b - d);
}
int X[] = {0, 0, 0, 1, -1};
int Y[] = {0, 1, -1, 0, 0};
int diss[110][110];
int main() {
    int T;
    cin >> T;
    const int inf = 1e9 + 7;
    while (T--) {
        int n, m, k;
        cin >> n >> m >> k;
        int dis[110][110];
        char mp[n][m];
        queue<pair<int, int>> q;
        int sx, sy, ex, ey;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                cin >> mp[i][j];
                if (mp[i][j] == 'S') {
                    sx = i;
                    sy = j;
                }
                if (mp[i][j] == 'E') {
                    ex = i;
                    ey = j;
                }
                dis[i][j] = inf;
            }
        }
        dis[sx][sy] = 0;
        q.push(make_pair(sx, sy));
        while (!q.empty()) {
            int x = q.front().first;
            int y = q.front().second;
            q.pop();
            queue<pair<int, int>> q2;
            q2.push(make_pair(x, y));
            while (!q2.empty()) {
                int xx = q2.front().first;
                int yy = q2.front().second;
                q2.pop();
                for (int i = 1; i <= 4; i++) {
                    int nx = xx + X[i];
                    int ny = yy + Y[i];
                    if (diss[nx][ny] != inf) continue;
                    if (nx < 1 || nx > n || ny < 1 || ny > m ||
                        mp[nx][ny] == '#')
                        continue;
                    diss[nx][ny] = diss[xx][yy]+1;
                    if(diss[nx][ny] == k+1) continue;
                    q2.push(make_pair(nx, ny));

                    if (mp[nx][ny] != 'M') {
                        if (dis[nx][ny] == inf) {
                            q.push(make_pair(nx, ny));
                            dis[nx][ny] = dis[x][y] + 1;
                        }
                    }
                }
            }
        }
        if (dis[ex][ey] != inf)
            cout << dis[ex][ey] << endl;
        else
            cout << -1 << endl;
    }
    return 0;
}